<template>
  <div class="layout">
    <el-container v-if="state.showMenu" class="container">
      <el-aside class="aside">
        <div class="head">
          <div>
            <img src="/images/logo.png" alt="logo">
            <span>后台管理</span>
          </div>
        </div>
        <div class="line" />
        <!-- 动态菜单 -->
        <el-menu
            background-color="#222832"
            text-color="#fff"
            :router="true"
            :default-openeds="state.defaultOpen"
            :default-active='state.currentPath'
            @select="handleMenuSelect"
        >
          <template v-for="menu in state.menus" :key="menu.menuId">
            <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.menuId.toString()">
              <template #title>
                <el-icon v-if="menu.menuIcon">
                  <component :is="getIconComponent(menu.menuIcon)" />
                </el-icon>
                <span>{{ menu.menuName }}</span>
              </template>
              <el-menu-item-group>
                <el-menu-item
                    v-for="child in menu.children"
                    :key="child.menuId"
                    :index="child.menuPath"
                >
                  <el-icon v-if="child.menuIcon">
                    <component :is="getIconComponent(child.menuIcon)" />
                  </el-icon>
                  {{ child.menuName }}
                </el-menu-item>
              </el-menu-item-group>
            </el-sub-menu>
            <el-menu-item v-else :index="menu.menuPath">
              <el-icon v-if="menu.menuIcon">
                <component :is="getIconComponent(menu.menuIcon)" />
              </el-icon>
              <span>{{ menu.menuName }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      <el-container class="content">
        <Header />
        <!-- 标签页区域 -->
        <div class="tabs-container" v-if="state.tabs.length > 0">
          <el-tabs
              v-model="state.activeTab"
              type="card"
              closable
              @tab-click="handleTabClick"
              @tab-remove="handleTabRemove"
          >
            <el-tab-pane
                v-for="tab in state.tabs"
                :key="tab.path"
                :label="tab.title"
                :name="tab.path"
            >
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="main">
          <router-view />
        </div>
        <Footer />
      </el-container>
    </el-container>
    <el-container v-else class="container">
      <router-view />
    </el-container>
  </div>
</template>

<script setup>
import { reactive, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { localGet, pathMap } from '@/utils'
import { localSet } from "./utils";
import { getMenus } from '@/utils/menu'

// 导入 Element Plus 图标
import {
  Odometer,
  Plus,
  Picture,
  StarFilled,
  Sell,
  ShoppingCart,
  Menu,
  Goods,
  User,
  List,
  Lock,
  Setting
} from '@element-plus/icons-vue'

// 不需要显示菜单和标签页的路由
const noMenu = ['/login']
// 需要显示菜单但不需要标签页的路由（通常是弹窗式页面）
const noTabs = ['/add', '/good/edit'] // 根据你的实际路由路径调整

const router = useRouter()
const route = useRoute()

const state = reactive({
  showMenu: true,
  defaultOpen: ['1', '2', '3', '4'],
  currentPath: '/',
  tabs: [],
  activeTab: '',
  menus: [] // 动态菜单数据
})

// 图标映射
const iconComponents = {
  Odometer,
  Plus,
  Picture,
  StarFilled,
  Sell,
  ShoppingCart,
  Menu,
  Goods,
  User,
  List,
  Lock,
  Setting
}

// 获取图标组件
const getIconComponent = (iconName) => {
  return iconComponents[iconName] || ''
}

// 静态路径标题映射（确保首页有标题）
const staticPathTitleMap = {
  '/': '首页',
  '/add': '添加商品',
  '/swiper': '轮播图配置',
  '/hot': '热销商品配置',
  '/new': '新品上线配置',
  '/recommend': '为你推荐配置',
  '/category': '分类管理',
  '/good': '商品管理',
  '/guest': '会员管理',
  '/order': '订单管理',
  '/account': '修改密码',
  '/user': '用户管理',
  '/role': '角色管理',
  '/menu': '菜单管理',
  '/goods-report': '商品汇总表'
}

// 页面标题映射（初始化为静态映射）
const pathTitleMap = reactive({ ...staticPathTitleMap })

// 获取动态菜单
const fetchMenus = async () => {
  try {
    const res = await getMenus()
    console.log('菜单数据:', res) // 调试用

    if (res && Array.isArray(res)) {
      state.menus = res
      buildPathTitleMap(state.menus)

      // 设置默认展开的菜单
      state.defaultOpen = state.menus.map(menu => menu.menuId.toString())
    } else {
      console.warn('菜单数据格式不正确，使用默认菜单')
      state.menus = getDefaultMenus()
      buildPathTitleMap(state.menus)
    }
  } catch (error) {
    console.error('获取菜单失败:', error)
    // 使用默认菜单作为后备
    state.menus = getDefaultMenus()
    buildPathTitleMap(state.menus)
  }
}

// 默认菜单（后备方案）- 添加首页路由
const getDefaultMenus = () => {
  return [
    {
      menuId: 1,
      menuName: 'Dashboard',
      menuIcon: 'Odometer',
      children: [
        {
          menuId: 2,
          menuName: '首页',
          menuPath: '/',
          menuIcon: 'Odometer'
        },
        {
          menuId: 3,
          menuName: '添加商品',
          menuPath: '/add',
          menuIcon: 'Plus'
        }
      ]
    },
    {
      menuId: 4,
      menuName: '首页配置',
      menuIcon: 'Picture',
      children: [
        {
          menuId: 5,
          menuName: '轮播图配置',
          menuPath: '/swiper',
          menuIcon: 'Picture'
        },
        {
          menuId: 6,
          menuName: '热销商品配置',
          menuPath: '/hot',
          menuIcon: 'StarFilled'
        },
        {
          menuId: 7,
          menuName: '新品上线配置',
          menuPath: '/new',
          menuIcon: 'Sell'
        },
        {
          menuId: 8,
          menuName: '为你推荐配置',
          menuPath: '/recommend',
          menuIcon: 'ShoppingCart'
        }
      ]
    },
    {
      menuId: 9,
      menuName: '模块管理',
      menuIcon: 'Menu',
      children: [
        {
          menuId: 10,
          menuName: '分类管理',
          menuPath: '/category',
          menuIcon: 'Menu'
        },
        {
          menuId: 11,
          menuName: '商品管理',
          menuPath: '/good',
          menuIcon: 'Goods'
        },
        {
          menuId: 12,
          menuName: '会员管理',
          menuPath: '/guest',
          menuIcon: 'User'
        },
        {
          menuId: 13,
          menuName: '订单管理',
          menuPath: '/order',
          menuIcon: 'List'
        }
      ]
    },
    {
      menuId: 14,
      menuName: '系统管理',
      menuIcon: 'Lock',
      children: [
        {
          menuId: 15,
          menuName: '修改密码',
          menuPath: '/account',
          menuIcon: 'Lock'
        }
      ]
    }
  ]
}

// 递归构建路径标题映射
const buildPathTitleMap = (menus) => {
  menus.forEach(menu => {
    if (menu.menuPath) {
      pathTitleMap[menu.menuPath] = menu.menuName
    }
    if (menu.children) {
      buildPathTitleMap(menu.children)
    }
  })
  console.log('路径标题映射:', pathTitleMap) // 调试用
}

// 获取页面标题 - 修复首页标题问题
const getPageTitle = (path, name) => {
  console.log('获取页面标题:', { path, name }) // 调试用

  // 优先使用路由名称
  if (name && pathMap[name]) {
    return pathMap[name]
  }
  // 其次使用路径映射
  if (pathTitleMap[path]) {
    return pathTitleMap[path]
  }
  // 最后使用静态映射
  if (staticPathTitleMap[path]) {
    return staticPathTitleMap[path]
  }
  return '未知页面'
}

// 初始化标签页 - 修复首页标签
const initTabs = () => {
  const savedTabs = localGet('tabs')
  if (savedTabs && Array.isArray(savedTabs)) {
    state.tabs = savedTabs
  }
  // 添加首页标签
  if (state.tabs.length === 0) {
    const homeTitle = getPageTitle('/', 'Home') // 确保首页有正确标题
    state.tabs.push({
      title: homeTitle,
      path: '/'
    })
    state.activeTab = '/'
  }
}

// 保存标签页到本地存储
const saveTabs = () => {
  localSet('tabs', state.tabs)
}

// 处理菜单选择
const handleMenuSelect = (index) => {
  console.log('菜单选择:', index, '标题:', pathTitleMap[index]) // 调试用

  // 如果是不需要标签页的路由，直接跳转不添加标签
  if (noTabs.includes(index)) {
    router.push(index)
    return
  }
  // 使用增强的标题获取方法
  const title = getPageTitle(index)
  addTab(title, index)
}

// 添加标签页
const addTab = (title, path) => {
  // 检查是否是不需要标签页的路由
  if (noTabs.includes(path)) {
    return
  }

  const existingTab = state.tabs.find(tab => tab.path === path)
  if (!existingTab) {
    state.tabs.push({
      title,
      path
    })
  }
  state.activeTab = path
  saveTabs()
}

// 处理标签点击
const handleTabClick = (tab) => {
  const path = tab.paneName
  router.push(path)
  state.currentPath = path
}

// 处理标签关闭
const handleTabRemove = (path) => {
  if (state.tabs.length === 1) {
    return // 至少保留一个标签
  }

  const index = state.tabs.findIndex(tab => tab.path === path)
  if (index !== -1) {
    state.tabs.splice(index, 1)

    // 如果关闭的是当前激活的标签，需要激活另一个标签
    if (path === state.activeTab) {
      const newActiveTab = state.tabs[Math.max(0, index - 1)].path
      state.activeTab = newActiveTab
      router.push(newActiveTab)
      state.currentPath = newActiveTab
    }

    saveTabs()
  }
}

// 监听路由变化 - 同时监听 path 和 name
watch(
    () => ({ path: route.path, name: route.name }),
    (newRoute, oldRoute) => {
      if (!noMenu.includes(newRoute.path)) {
        // 检查是否是不需要标签页的路由
        if (noTabs.includes(newRoute.path)) {
          return
        }

        const title = getPageTitle(newRoute.path, newRoute.name)
        console.log('路由变化，添加标签:', { path: newRoute.path, title }) // 调试用

        // 避免重复添加相同的标签
        if (newRoute.path !== oldRoute?.path) {
          addTab(title, newRoute.path)
        }
      }
    },
    { immediate: true, deep: true }
)

// 路由守卫 - 只处理权限和菜单显示，不处理标签页
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next()
  } else {
    if (!localGet('token')) {
      next({ path: '/login' })
    } else {
      next()
    }
  }
  state.showMenu = !noMenu.includes(to.path)
  state.currentPath = to.path
  // 使用增强的标题获取方法
  document.title = getPageTitle(to.path, to.name)
})

// 初始化
onMounted(() => {
  initTabs()
  fetchMenus()
})
</script>

<style scoped>
.layout {
  min-height: 100vh;
  background-color: #ffffff;
}
.container {
  height: 100vh;
}
.aside {
  width: 200px!important;
  background-color: #222832;
}
.head {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
}
.head > div {
  display: flex;
  align-items: center;
}

.head img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}
.head span {
  font-size: 20px;
  color: #ffffff;
}
.line {
  border-top: 1px solid hsla(0,0%,100%,.05);
  border-bottom: 1px solid rgba(0,0,0,.2);
}
.content {
  display: flex;
  flex-direction: column;
  max-height: 100vh;
  overflow: hidden;
}
.tabs-container {
  background: #fff;
  padding: 0 10px;
  border-bottom: 1px solid #e4e7ed;
}
.main {
  height: calc(100vh - 140px);
  overflow: auto;
  padding: 10px;
}
</style>

<style>
body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.el-menu {
  border-right: none!important;
}
.el-submenu {
  border-top: 1px solid hsla(0, 0%, 100%, .05);
  border-bottom: 1px solid rgba(0, 0, 0, .2);
}
.el-submenu:first-child {
  border-top: none;
}
.el-submenu [class^="el-icon-"] {
  vertical-align: -1px!important;
}
a {
  color: #409eff;
  text-decoration: none;
}
.el-pagination {
  text-align: center;
  margin-top: 20px;
}
.el-popper__arrow {
  display: none;
}

/* 标签页样式优化 */
.el-tabs__header {
  margin: 0;
}
.el-tabs--card>.el-tabs__header .el-tabs__nav {
  border: none;
}
.el-tabs--card>.el-tabs__header .el-tabs__item {
  border: none;
  border-radius: 4px 4px 0 0;
  margin-right: 4px;
}
</style>
